package cn.achao.csr.chat.core.event.listener;

import cn.achao.csr.api.model.entity.ChatContact;
import cn.achao.csr.api.model.entity.ChatGroupMember;
import cn.achao.csr.api.model.entity.ChatUser;
import cn.achao.csr.chat.core.build.ChatContactAdapter;
import cn.achao.csr.chat.core.build.GroupMemberAdapter;
import cn.achao.csr.chat.core.event.UserRegisterEvent;
import cn.achao.csr.chat.dao.ChatContactDao;
import cn.achao.csr.chat.dao.ChatGroupMemberDao;
import cn.achao.csr.chat.dao.ChatUserDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户上线监听器
 *
 * @author achao
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserRegisterListener {

    private final ChatUserDao userDao;
    private final ChatContactDao contactDao;
    private final ChatGroupMemberDao groupMemberDao;


    /**
     * 新用户注册事件监听器
     * @param event
     */
    @Async
    @EventListener(classes = UserRegisterEvent.class)
    public void sendCard(UserRegisterEvent event) {
        ChatUser user = event.getUser();
        log.info("用户【{}】注册了...", user.getNickName());
        // 加入大厅群聊
        ChatContact contact = ChatContactAdapter.buildDefaultContact(user.getId());
        // 赋予群聊角色
        ChatGroupMember chatGroupMember = GroupMemberAdapter.buildDefaultGroupMember(user.getId());

        contactDao.save(contact);
        groupMemberDao.save(chatGroupMember);
    }

}
